﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SmartSiteManagementSystem.AdminWeb.Extensions;
using SmartSiteManagementSystem.AdminWeb.Filter;
using SmartSiteManagementSystem.AdminWeb.Models;
using SmartSiteManagementSystem.IServices;
using SmartSiteManagementSystem.Models.Admin;
using SmartSiteManagementSystem.Models.DTO;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace SmartSiteManagementSystem.AdminWeb.Controllers
{

    [TypeFilter(typeof(LoginAuthorizeAttribute))]
    public class AdminGroupController : AdminBaseControllers
    {
        private readonly ILogger<AdminGroupController> _logger;
        //注入后台服务
        private readonly IAdminService _adminService;
        public AdminGroupController(IAdminService adminService, ILogger<AdminGroupController> logger) : base(adminService)
        {
            _logger = logger;
            _adminService = adminService;
        }
        /// <summary>
        /// 首页  
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="name"></param>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        public JsonResult GetList(string name, int page = 0, int rows = 50)
        {
            if (page < 1)
            {
                page = 1;
            }
            page = (page - 1) * rows;

            Hashtable param = new Hashtable();
            param.Add("is_deleted", 0);//正常 0 false
            if (!string.IsNullOrEmpty(name))
                param.Add("group_name", name);

            int count = _adminService.GetAdminGroupCount(param);
 
            IList<AdminGroupInfo> list = _adminService.GetAdminGroupList(param, "SortOrder desc", page, rows);

            var data = new
            {
                total = count,
                rows = list
            };
            return Json(data);
        }

        /// <summary>
        /// 添加或修改
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Access(int id = 0)
        {
            AdminGroupInfo adminGroupInfo = new AdminGroupInfo();
            if (id > 0)
            {
                adminGroupInfo = _adminService.GetAdminGroupById(id);
            }
            ViewBag.adminGroupInfo = adminGroupInfo;
            return View();
        }

        /// <summary>
        /// 菜单列表
        /// </summary>
        /// <param name="adminGroupId"></param>
        /// <returns></returns>
        public ActionResult MenuList(int adminGroupId)
        {
            ViewBag.adminGroupId = adminGroupId;
            return View();
        }

        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <param name="adminGroupId"></param>
        /// <returns></returns>
        public JsonResult GetMenuList(int adminGroupId)
        {
            IList<AdminMenuInfo> menulist = _adminService.GetAllMenuInfoList();
            IEnumerable<AdminMenuInfo> menuList = menulist.Where(m => m.ParentId == 0);

            AdminGroupInfo adminGroupInfo = _adminService.GetAdminGroupById(adminGroupId);
            IList<AdminUserGroupMenuInfo> adminUserMenuList = _adminService.GetAllAdminUserGroupMenuListByadminUserId(adminGroupId);
            IList<int> adminuserIds = (from item in adminUserMenuList select item.AdminMenuId).ToList();

            Hashtable param = new Hashtable();
            param.Add("AdminUserGroupId", adminGroupId);
            IList<AdminGroupBtnRelInfo> relList = _adminService.GetAdminGroupBtnRelInfoList(param, "", 0, 3000);
            IList<int> adminGroupBtnRelIds = (from item in relList select item.BtnId * 100000).ToList();

            ViewBag.adminGroupInfo = adminGroupInfo;

            var lr = from l in menuList
                     join r in adminUserMenuList on l.AdminMenuId equals r.AdminMenuId
                     into gj
                     from subl in gj.DefaultIfEmpty()
                     select new { l.AdminMenuId, l.MenuName, l.StopFlag, l.ParentId, l.IsParent, TmpFlag = false };

            IList<AdminMenuInfo> lrList = new List<AdminMenuInfo>();
            foreach (var item in lr)
            {
                AdminMenuInfo adminMenuInfo = new AdminMenuInfo();
                adminMenuInfo.AdminMenuId = item.AdminMenuId;
                adminMenuInfo.MenuName = item.MenuName;
                adminMenuInfo.IsParent = item.IsParent;
                adminMenuInfo.IsChecked = adminuserIds.Contains(item.AdminMenuId);
                lrList.Add(adminMenuInfo);
            }
            List<TreeModel> tree = new List<TreeModel>();
            List<Hashtable> hsTree = new List<Hashtable>();
            foreach (var item in lrList)
            {
                Hashtable hs = new Hashtable();
                hs.Add("id", item.AdminMenuId);
                hs.Add("text", item.MenuName);
                if (item.IsParent)
                    hs.Add("children", GetTreeChild(adminGroupId, menulist, item, adminuserIds, adminGroupBtnRelIds));
                else
                    //按钮
                    hs.Add("children", GetBtnList(adminGroupId, item.AdminMenuId, adminGroupBtnRelIds));

                if ((item.AdminMenuId > 100000 && item.AdminMenuId % 100000 == 0))
                {
                    hs.Add("checked", item.IsChecked);
                }
                else
                {
                    hs.Add("checked", adminuserIds.Contains(item.AdminMenuId));
                }
                //easyui-tree 会自动级联选中，所以只需要设置最底层的菜单或者按钮为选中状态即可，只要有子级，均设置为false 可以保证数据展示正确；fuzhi.zhao 2017.01.19
                if (hs["children"] != null && ((List<Hashtable>)hs["children"]).Count > 0)
                {
                    hs["checked"] = false;
                }
                hsTree.Add(hs);
            }

            //return Json(hsTree, JsonRequestBehavior.AllowGet);
            return Json(hsTree);
        }

        /// <summary>
        /// 获取按钮列表
        /// </summary>
        /// <param name="adminGroupId"></param>
        /// <param name="menuId"></param>
        /// <param name="adminGroupBtnRelIds"></param>
        /// <returns></returns>
        private List<Hashtable> GetBtnList(int adminGroupId, int menuId, IList<int> adminGroupBtnRelIds)
        {
            List<Hashtable> hsTree = new List<Hashtable>();

            //为防止btn的ID与Menu的Id重复，将btn中的id*100000
            IList<AdminPageBtnInfo> btnList = _adminService.GetAdminPageBtnInfoList(menuId);
            foreach (var item in btnList)
            {
                if ((item.BtnId > 100000 && item.BtnId % 100000 == 0) || item.BtnId < 100000)
                {
                    Hashtable hs = new Hashtable();
                    hs.Add("id", item.BtnId);
                    hs.Add("text", item.BtnName);
                    hs.Add("children", GetBtnList(adminGroupId, item.BtnId, adminGroupBtnRelIds));
                    hs.Add("checked", adminGroupBtnRelIds.Contains(item.BtnId));
                    if (hs["children"] != null && ((List<Hashtable>)hs["children"]).Count > 0)
                    {
                        hs["checked"] = false;
                    }
                    hsTree.Add(hs);

                }
            }

            return hsTree;
        }

        /// <summary>
        /// 获取子数据
        /// </summary>
        /// <param name="adminGroupId"></param>
        /// <param name="menulist"></param>
        /// <param name="curNode"></param>
        /// <param name="adminMenuIds"></param>
        /// <param name="adminGroupBtnRelIds"></param>
        /// <returns></returns>
        private List<Hashtable> GetTreeChild(int adminGroupId, IList<AdminMenuInfo> menulist, AdminMenuInfo curNode, IList<int> adminMenuIds, IList<int> adminGroupBtnRelIds)
        {
            IEnumerable<AdminMenuInfo> childlist = menulist.Where(m => m.ParentId == curNode.AdminMenuId);

            List<Hashtable> hsTree = new List<Hashtable>();
            foreach (var item in childlist)
            {
                Hashtable hs = new Hashtable();
                hs.Add("id", item.AdminMenuId);
                hs.Add("text", item.MenuName);
                if (item.IsParent)
                {
                    hs.Add("children", GetTreeChild(adminGroupId, menulist, item, adminMenuIds, adminGroupBtnRelIds));
                }
                else
                {
                    hs.Add("children", GetBtnList(adminGroupId, item.AdminMenuId, adminGroupBtnRelIds));
                    hs.Add("checked", adminMenuIds.Contains(item.AdminMenuId));
                }
                if (hs["children"] != null && ((List<Hashtable>)hs["children"]).Count > 0)
                {
                    hs["checked"] = false;
                }
                hsTree.Add(hs);
            }
            return hsTree;
        }

        /// <summary>
        /// 添加、编辑操作
        /// </summary>
        /// <param name="AdminUserGroupId"></param>
        /// <param name="AdminUserGroupName"></param>
        /// <param name="Code"></param>
        /// <param name="Email"></param>
        /// <param name="SortOrder"></param>
        /// <param name="Remark"></param>
        public JsonResult ajaxAccess(int AdminUserGroupId, string AdminUserGroupName, string Code, string Email, int SortOrder, string Remark)
        {
            AdminGroupInfo adminGroup = null;
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 200;
            result.Msg = "操作失败!";
            if (AdminUserGroupId > 0)
            {
                adminGroup = _adminService.GetAdminGroupById(AdminUserGroupId);
            }
            else
            {
                adminGroup = new AdminGroupInfo();
            }
            adminGroup.DeleteFlag = false;
            adminGroup.Email = Email;
            adminGroup.Remark = Remark;
            adminGroup.StopFlag = false;
            adminGroup.AdminUserGroupName = AdminUserGroupName;
            adminGroup.SortOrder = SortOrder;
            adminGroup.Code = Code;

            if (AdminUserGroupId > 0)
            {
                adminGroup.UpdateTime = DateTime.Now;
                result.IsSuccess = _adminService.UpdateAdminUserGroup(adminGroup);

            }
            else
            {
                adminGroup.CreateTime = DateTime.Now;
                AdminUserGroupId = _adminService.InsertAdminUserGroup(adminGroup);
                result.IsSuccess = AdminUserGroupId > 0 ? true : false;
            }
            if (result.IsSuccess)
            {
                result.Msg = "操作成功!";
            }
            return Json(result);

        }

        /// <summary>
        /// 保存权限信息
        /// </summary>
        /// <param name="adminUserGroupId"></param>
        /// <param name="ids"></param>
        public JsonResult ajaxUpdateGroupMenu(int adminUserGroupId, string ids)
        {

            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 200;
            result.Msg = "操作失败!";

            if (adminUserGroupId > 0)
            {
                try
                {
                    _adminService.UpdateAdminUserGroupMenu(adminUserGroupId, ids);
                    result.IsSuccess = true;
                    result.Msg = "操作成功!";

                }
                catch (Exception ex)
                {
                    result.IsSuccess = false;
                    result.Msg = "操作失败!";
                }
            }
            else
            {
                result.IsSuccess = false;
                result.Msg = "请在页面上操作!";
            }
            return Json(result);
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="AdminUserGroupId"></param>
        public JsonResult ajaxUpdateState(int AdminUserGroupId)
        {
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 200;
            result.Msg = "操作失败!";
            AdminGroupInfo adminGroup = null;
            if (AdminUserGroupId > 0)
            {

                adminGroup = _adminService.GetAdminGroupById(AdminUserGroupId);
                adminGroup.UpdateTime = DateTime.Now;
                adminGroup.StopFlag = adminGroup.StopFlag ? false : true;
                result.IsSuccess = _adminService.UpdateAdminUserGroup(adminGroup);

            }
            if (result.IsSuccess)
            {
                result.Msg = "操作成功!";
            }
            return Json(result);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="AdminUserGroupId"></param>
        public JsonResult ajaxDelete(int AdminUserGroupId)
        {
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 200;
            result.Msg = "操作失败!";
            if (AdminUserGroupId > 0)
            {
                AdminGroupInfo adminGroup = _adminService.GetAdminGroupById(AdminUserGroupId);
                if (adminGroup != null)
                {
                    adminGroup.DeleteFlag = true;
                    result.IsSuccess = _adminService.UpdateAdminUserGroup(adminGroup);
                }
            }
            if (result.IsSuccess)
            {
                result.Msg = "成功删除!";
            }
            return Json(result);
        }


    }
}
